import cv2

# Open the camera
cam = cv2.VideoCapture(0)
if not cam.isOpened():
    print("Error: Camera could not be opened.")
    exit()

ret, frame = cam.read()
if not ret:
    print("Failed to capture video frame.")
    cam.release()
    exit()

h, w = frame.shape[: 2]

# Initialize the writer
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
video_write = cv2.VideoWriter('videos/video.avi', fourcc, 25.0, (w, h))

while cam.isOpened():
    ret, frame = cam.read()
    if not ret:
        print("Failed to read video frame.")
        break

    video_write.write(frame)
    cv2.imshow('video', frame)

    # Press 'Q' to exit
    if cv2.waitKey(1) & 0xFF == ord('Q'):
        break

cam.release()
video_write.release()
cv2.destroyAllWindows()